<template>
	<div>
		<!-- 面包屑 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/layout' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>定时任务</el-breadcrumb-item>
			<el-breadcrumb-item>任务列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片布局 -->
		<el-card>
			<!-- 植入搜索栏 -->
			<el-row :gutter="20">
				<el-col :span="5"><el-input clearable placeholder="搜索bean" v-model="searchBean" clearableclear="getJobList"></el-input></el-col>
				<el-col :span="5"><el-input clearable placeholder="搜索方法名称" v-model="searchMethod" clearableclear="getJobList"></el-input></el-col>
				<el-col :span="5"><el-input clearable placeholder="搜索cron" v-model="searchCron" clearableclear="getJobList"></el-input></el-col>

				<el-col :span="2">
					<el-button type="primary" @click="getJobList()">
						<el-icon><Search /></el-icon>
					</el-button>
				</el-col>
				<el-col :span="5"><el-button type="primary" @click="showAddBox = true">添加定时任务</el-button></el-col>
			</el-row>
			<!-- 放入table -->
			<el-table
				:data="jobs"
				style="width: 100%; height: 550px; margin-top:10px;"
				border
				:header-cell-style="{ height: '37px', padding: '0' }"
				:row-style="{ height: '37px' }"
				:cell-style="{ padding: '0' }"
			>
				<!-- 数据绑定 -->
				<el-table-column fixed label="作业id" width="80" prop="id"></el-table-column>
				<el-table-column fixed label="bean名称" width="150" prop="beanName"></el-table-column>
				<el-table-column fixed label="方法名称" width="180" prop="methodName"></el-table-column>
				<el-table-column label="方法参数" width="120" prop="methodParams"></el-table-column>
        <el-table-column label="作业状态" width="200" prop="enable">
          <template #default="scope">
              <el-switch
                  v-model="scope.row.enable"
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                  active-text="启用"
                  inactive-text="关闭"
                  active-value="0"
                  inactive-value="1"
                  @click="changeJob(scope.row)"
              />
          </template>
        </el-table-column>
				<el-table-column label="Cron 表达式" width="120" prop="cronExpression">
					<template #default="scope">
						<el-tag size="small">{{ scope.row.cronExpression }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="备注信息" width="200" prop="remark"></el-table-column>
				<el-table-column label="可用性" width="100" prop="enable"></el-table-column>
				<el-table-column label="是否锁定" width="100" prop="lockable"></el-table-column>
				<el-table-column label="创建者" width="80" prop="createBy"></el-table-column>
				<el-table-column label="创建时间" width="200" prop="createDate"></el-table-column>
				<el-table-column label="最近修改人" width="100" prop="updateBy"></el-table-column>
				<el-table-column label="最近修改" width="200" prop="lastUpdate"></el-table-column>
				<el-table-column fixed="right" label="操作" width="150">
					<template #default="scope">
						<el-button size="small" @click="showEdit(scope.row)">编辑</el-button>
						<el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页模块 -->
			<el-pagination
				v-model:current-page="pageNo"
				v-model:page-size="pageSize"
				:page-sizes="[10, 20, 50, 100]"
				:small="false"
				:disabled="false"
				:background="true"
				layout="total, sizes, prev, pager, next"
				:total="totalCount"
				@size-change="onSizeChange"
				@current-change="onPageChange"
			/>
			<!-- 添加会话框 -->
			<el-dialog title="新增定时任务" v-model="showAddBox" width="40%" :before-close="clearEdit" style="padding: 8px 15px;" @close="onClose">
				<el-form :model="jobFrom" :rules="jobFromRules" ref="jobFromRules" label-width="120px">
					<!-- <el-form-item label="bean名称"prop="beanName">
						<el-select @change="setBean" v-model="jobFrom.beanName" filterable allow-create default-first-option :reserve-keyword="false" placeholder="选择或新建Bean">
							<el-option v-for="item in beanOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item> -->
					<el-form-item label="bean名称" prop="beanName"><el-input v-model="jobFrom.beanName"></el-input></el-form-item>
					<el-form-item label="方法名称" prop="methodName"><el-input v-model="jobFrom.methodName"></el-input></el-form-item>
					<el-form-item label="方法参数" prop="methodParams"><el-input placeholder="多参数请使用逗号','分隔" v-model="jobFrom.methodParams"></el-input></el-form-item>
					<el-form-item label="Cron 表达式" prop="cronExpression"><el-input v-model="jobFrom.cronExpression"></el-input></el-form-item>
					<el-form-item label="备注信息" prop="remark"><el-input :rows="2" type="textarea" v-model="jobFrom.remark"></el-input></el-form-item>
					<el-form-item label="是否立即启用" prop="enable">
						<template #default="scope">
							<el-switch
								v-model="jobFrom.enable"
								active-color="#13ce66"
								inactive-color="#ff4949"
								active-text="是"
								:active-value="0"
								:inactive-value="1"
								inactive-text="否"
							></el-switch>
						</template>
					</el-form-item>

					<el-form-item class="dialog-footer">
						<el-button @click="clearEdit">取消</el-button>
						<el-button type="primary" @click="saveJobData('jobFromRules')">确定</el-button>
					</el-form-item>
				</el-form>
			</el-dialog>

      <!-- 修改会话框 -->
      <el-dialog title="修改定时任务" v-model="showEditBox" width="40%" :before-close="clearEdit" style="padding: 8px 15px;" @close="onClose">
        <el-form :model="jobFrom" :rules="jobFromRules" ref="jobFromRules" label-width="120px">
          <!-- <el-form-item label="bean名称"prop="beanName">
            <el-select @change="setBean" v-model="jobFrom.beanName" filterable allow-create default-first-option :reserve-keyword="false" placeholder="选择或新建Bean">
              <el-option v-for="item in beanOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="bean名称" prop="beanName"><el-input v-model="jobFrom.beanName"></el-input></el-form-item>
          <el-form-item label="方法名称" prop="methodName"><el-input v-model="jobFrom.methodName"></el-input></el-form-item>
          <el-form-item label="方法参数" prop="methodParams"><el-input v-model="jobFrom.methodParams"></el-input></el-form-item>
          <el-form-item label="Cron 表达式" prop="cronExpression"><el-input v-model="jobFrom.cronExpression"></el-input></el-form-item>
          <el-form-item label="备注信息" prop="remark"><el-input :rows="2" type="textarea" v-model="jobFrom.remark"></el-input></el-form-item>
          <el-form-item label="是否立即启用" prop="enable">
            <template #default="scope">
              <el-switch
                  v-model="jobFrom.enable"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="是"
                  :active-value="0"
                  :inactive-value="1"
                  inactive-text="否"
              ></el-switch>
            </template>
          </el-form-item>

          <el-form-item class="dialog-footer">
            <el-button @click="clearEdit">取消</el-button>
            <el-button type="primary" @click="handleEdit('jobFromRules')">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
		</el-card>
	</div>
</template>

<script>
import { ElMessage } from 'element-plus';
import {deleteJob, getJobList, saveJob, updateJob} from '@/api/job';
import {getMenuList} from "@/api/menu";
export default {
	data() {
		return {
			beanOptions: [],

			jobs: [],
			showAddBox: false,
      showEditBox:false,

			searchBean: '',
			searchMethod: '',
			searchCron: '',

			pageNo: 1,
			pageSize: 10,
			totalCount: 0,

			jobFrom: [],
			jobFromRules: {
				beanName: [
					{
						required: true,
						message: '请输入bean名称',
						trigger: 'blur'
					},
					{
						required: true,
						pattern: /^[a-zA-Z]+$/,
						message: '方法名称仅为字母组成',
						trigger: 'blur'
					}
				],
				methodName: [
					{ required: true, message: '请输入方法名称', trigger: 'blur' },
					{
						required: true,
						pattern: /^[a-zA-Z]+$/,
						message: '方法名称仅为字母组成',
						trigger: 'blur'
					}
				],
				methodParams: [
          {
            required: false,
            pattern: /^[a-zA-Z0-9]+([,][a-zA-Z0-9]+)*$/,
            message: '仅允许输入数字或者字母作为参数，且请正确使用分隔符',
            trigger: "blur"
          }
				],

				cronExpression: [
					{
						required: true,
						message: '请输入cron表达式',
						trigger: 'blur'
					}
				]
			}
		};
	},
	methods: {
		onClose() {
			this.jobFrom = [];

			//关闭弹框
			this.showAddBox = false;
			this.showEditBox = false;
		},
		clearEdit() {
			//清空表单默认值
			this.jobFrom = [];
			//关闭弹框
			this.showAddBox = false;
			this.showEditBox = false;
		},

		onSizeChange(pageSize) {
			this.pageNo = 1;
			this.pageSize = pageSize;
			this.getJobList();
		},
		onPageChange(page) {
			this.pageNo = page;
			this.getJobList();
		},

		saveJobData(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					this.$confirm('此操作将添加该定时任务, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(()=>{
            const data = {
              id: this.jobFrom.id,
              enable: this.jobFrom.enable,
              remark:this.jobFrom.remark,
              beanName: this.jobFrom.beanName,
              methodName: this.jobFrom.methodName,
              methodParams: this.jobFrom.methodParams,
              cronExpression: this.jobFrom.cronExpression,

            };
            // console.log(this.jobFrom)
            saveJob(data).then(resp=>{
              if (resp.success){
                this.onClose()
                ElMessage.success("添加任务成功")
                this.getJobList();
              }
            })
          }).catch(ex=>{
            console.log(ex)
          });
				}
			});
		},
    handleEdit(formName){
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$confirm('此操作将修改该定时任务, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(()=>{
            const data = {
              id: this.jobFrom.id,
              enable: this.jobFrom.enable,
              remark:this.jobFrom.remark,
              beanName: this.jobFrom.beanName,
              methodName: this.jobFrom.methodName,
              methodParams: this.jobFrom.methodParams,
              cronExpression: this.jobFrom.cronExpression,

            };
            console.log(this.jobFrom)
            updateJob(data).then(resp=>{
              if (resp.success){
                this.onClose()
                ElMessage.success("修改成功")
                this.getJobList();
              }
            })
          }).catch(ex=>{
            console.log(ex)
          });
        }
      });
    },
		handleDelete(index, row) {
			this.$confirm('此操作将永久删除该任务, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					const delId = { id: row.id };
					deleteJob(delId).then(resp => {
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						this.getJobList();
					});
				})
				.catch(ex => {
					this.$message({
						type: 'error',
						message: '删除失败！' + ex
					});
				});
		},
		changeJob(row) {
			const data = {
				id: row.id,
				enable: row.enable,
				beanName: row.beanName,
        remark:this.jobFrom.remark,
				methodName: row.methodName,
				methodParams: row.methodParams,
				cronExpression: row.cronExpression
			};
			console.log(data);
			updateJob(data).then(resp => {
				if (resp.success) {
					ElMessage.success('修改成功');
				}
			});
		},
    showEdit(row){
      //设置id
      this.jobFrom.id = row.id;

      //设置表单默认值
      this.jobFrom.enable = row.enable;
      this.jobFrom.beanName = row.beanName;
      this.jobFrom.remark = row.remark;
      this.jobFrom.methodName = row.methodName;
      this.jobFrom.methodParams = row.methodParams;
      this.jobFrom.cronExpression = row.cronExpression;
      //弹框
      this.showEditBox = true;
    },
		setBean() {
			//从包里获取包中含有的类
			//最好能顺便获取包中的方法
		},
    getJobList(){
      this.searchStr = {
        bean: this.searchBean,
        method: this.searchMethod,
        cron:this.searchCron
      };
      const param = { page: this.pageNo, limit: this.pageSize, searchStr: this.searchStr };

      getJobList(param).then(resp => {
        this.totalCount = resp.total;
        this.jobs = resp.rows;
        // console.log('-----------------------');
        // console.log(this.tableData)
      });
    }
	},
	mounted() {
		const param = { page: '', limit: '' };
		getJobList(param).then(resp => {
      console.log(resp)
			this.jobs = resp.rows;
		});
	}
};
</script>

<style scoped>
div.el-breadcrumb {
	height: 45px;
}

.el-dialog__body {
	padding: 0px 15px;
}

.el-form-item {
	/* height: 68px; */
}
</style>
